using MediatR;
using Microsoft.EntityFrameworkCore;
using SupplierCustomerManagement.Infrastructure;
using SupplierCustomerManagement.Read.API.Applications.Commands.breeding;
using SupplierCustomerManagement.Read.API.Dtos.Breeding;

namespace SupplierCustomerManagement.Read.API.Applications.CommandHandlters.breeding
{
    public class GetStatusDistributionQueryHandler : IRequestHandler<GetStatusDistributionQuery, StatusDistributionDto>
    {
        private readonly SupplierDbContext _db;
        private readonly ILogger<GetStatusDistributionQueryHandler> _logger;

        public GetStatusDistributionQueryHandler(SupplierDbContext db, ILogger<GetStatusDistributionQueryHandler> logger)
        {
            _db = db;
            _logger = logger;
        }

        public async Task<StatusDistributionDto> Handle(GetStatusDistributionQuery request, CancellationToken cancellationToken)
        {
            // 口径：按 Sheep.CurrentStatus 统计当前状态分布，可选按 FarmId 过滤。
            var query = _db.Sheeps.AsNoTracking().AsQueryable();
            if (request.FarmId.HasValue)
            {
                query = query.Where(s => s.FarmId == request.FarmId.Value);
            }

            var grouped = await query
                .GroupBy(s => s.CurrentStatus)
                .Select(g => new { Status = g.Key, Count = g.Count() })
                .ToListAsync(cancellationToken);

            var total = grouped.Sum(x => x.Count);
            var categories = grouped.Select(x => x.Status).ToList();
            var data = grouped.Select(x => new StatusItemDto
            {
                name = x.Status,
                value = x.Count,
                percentage = total == 0 ? "0%" : string.Format("{0:P0}", (double)x.Count / total)
            }).ToList();

            return new StatusDistributionDto
            {
                categories = categories,
                data = data
            };
        }
    }
}
